package com.kezesong.leasing.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kezesong.leasing.controller.response.WeixinRspBody;
import com.kezesong.leasing.entity.UserInfoEntity;
import com.kezesong.leasing.mapper.UserInfoMapper;
import com.kezesong.leasing.service.UserInfoService;
import com.kezesong.leasing.service.WeixinService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    Logger logger = LoggerFactory.getLogger(getClass());




    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    WeixinService weixinService;

    @Override
    public UserInfoEntity getUserInfoByOpenId(String openId) {
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        if (StringUtils.isNotBlank(openId)){
            userInfoEntity.setOpenId(openId);
            UserInfoEntity result = userInfoMapper.selectOne(userInfoEntity);
            if (logger.isDebugEnabled()) {
                logger.debug("UserInfoServiceImpl.getUserInfoByOpenId openId:{}, result:{}", openId, JSON.toJSON(result));
            }
            return result;
        }
        return null;
    }

    @Override
    public int addUserInfo(UserInfoEntity userInfoEntity) {
        int result = userInfoMapper.insert(userInfoEntity);
        return result;
    }



    @Override
    public WeixinRspBody getWeixinInfo(String code) {
        WeixinRspBody rspBody = new WeixinRspBody();
        JSONObject userInfoJsonObject = weixinService.getWechatUserInfo(code);
        String openId = userInfoJsonObject.getString("openid");
        String unionId = userInfoJsonObject.getString("unionid");
        rspBody.setOpenId(openId);
        rspBody.setUnionId(unionId);
        return rspBody;
    }



}
